<template>
    <el-card class="application-edit">
        
        <div class="application-edit-tab flex items-start">
            <div @click="tabChange(0)" :class="'application-edit-tabitem flex-1 text-grey-darker text-center px-4 py-4'+ (tabIndex? '':' active')">
                创作企业专属应用
            </div>
            <div @click="tabChange(1)" :class="'application-edit-tabitem flex-1 text-grey-darker text-center px-4 py-4'+ (tabIndex ? ' active' :'')">
                关联企业入驻产品
            </div>
        </div>
        <div v-if="!tabIndex">
            <div class="application-edit__upload">
                <img-cropper-upload v-model="form.img" :config="{width: 900}" class="w-full">
                    <div class="active relative" v-if="form.img">
                        <img :src="form.img" style="max-height: 250px;">
                        <span class="delete-icon">
                            <i class="el-icon-error" @click.stop="form.img = ''"></i>
                        </span>
                    </div>
                    <div class="default text-center" v-else>
                        <i class="iconfont icon-camera"></i>
                        <div>请添加封面图片<br/>建议尺寸：900像素*500像素</div>
                    </div>
                </img-cropper-upload>
            </div>

            <!-- 标题 -->
            <input type="text" v-model="form.title" placeholder="请输入标题" class="application-edit__title border-b">

            <!-- 分类 -->
            <!-- <div class="flex items-center">
                <div class="flex items-center mr-4" v-for="(item, ind) in types" :key="ind">
                    <el-cascader
                        class="mr-2 mb-4"
                        v-model="types[ind]"
                        :options="typeOptions"
                        placeholder="请选择类目"
                        :show-all-levels="false"
                        :props="{value: 'id', label: 'text', children: 'nodes'}">
                    </el-cascader>
                    <i class="el-icon-close mb-4" @click="types.splice(ind, 1)"></i>
                </div>

                <span @click="addCategory" class="text-blue-light mb-4 flex-no-shrink">
                    <i class="el-icon-plus mr-2 text-xs"></i>添加
                </span>
            </div> -->

            <el-select
                class="mb-4 application-edit__tags border-b w-full"
                v-model="form.labels"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请填写标签，用回车分割">
            </el-select>

            <!-- 富文本 -->
            <tinymce v-model="form.html" :config="{}"></tinymce>

            <!-- btn-group -->
            <div class="flex justify-end items-center application-edit__control create-collaspe" >
                <!-- <el-checkbox v-model="form.hide">匿名发布</el-checkbox> -->
                <div>
                    <span style="color:#8795A1" class="mr-2" v-if="autoSaveTag">自动保存于{{saveTime | formatDate('yy-mm-ss hh:mm:ss') }}</span>
                    <el-button type="success" @click="$refs.preview.open(form)">预览</el-button>
                    <el-button type="primary" @click="postData(0)">保存</el-button>
                    <el-button class="btn-primary-md" @click="submitData">投稿</el-button>
                </div>
            </div>
        </div>
        <div class="mt-4" v-else>
            <el-table
            :data="enterPro"
            height="500"
        >
            <el-table-column label="品牌" align="center" >
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.manufactureName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="类目" align="center" >
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.cats.map(item => item.cnname).join('-') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="牌号" align="center">
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.productName  }}</span>
                </template>
            </el-table-column>
            <el-table-column label="产品名称" align="center">
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.name  }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="140"  >
                <template slot-scope="{row, $index}">
                    <el-button type="text"  @click="onDel(row.productid)" style="color: #E33A4F">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
            <div class="flex justify-center my-2">
                <el-button type="primary" @click="$refs.productList.open()">新增关联</el-button>
            </div>
        </div>

        <!-- 预览 -->
        <preview :source="form" :category-text="categoriesText" :labels="form.labels" ref="preview"></preview>

        <!-- 频道 -->
        <channel @reset="channelReset" @search="channelSearch($event)" @close="dialigClose" @typeChange="channelTypeChange" :channel-data.sync="category" @confirm='confirmChannel' :channel-selected="channelArray"  ref="channel"></channel>

        <!-- 新增关联 -->
        <product-list ref="productList" @confirm="selectedPro"></product-list>
    </el-card>
</template>

<script>
    import Tinymce from '../../components/base/Tinymce';
    import Preview from '../../components/widget/Preview';
    import Channel from '../../components/widget/Channel';
    import ProductList from '../../components/widget/ProductList'
    import FileUpload from '../../components/base/FileUpload';
    import ImgCropperUpload from '../../components/base/ImgCropperUpload';
    import {Cascader, Checkbox, Select , Popover} from 'element-ui';
    import {getCategorise} from '../../config/Cache';
    import debounce from 'lodash/debounce';
    

    export default {
        components: {
            Tinymce,
            Preview,
            Channel,
            ProductList,
            FileUpload,
            ImgCropperUpload,
            ElSelect: Select,
            ElCascader: Cascader,
            ElCheckbox: Checkbox,
            ElPopover: Popover,
        },
        data() {
            return {
                form: null,
                types: new Array(1),
                labels: [],
                typeOptions: [],
                options: [],
                isCollapse: document.body.clientWidth < 1024,
                category:[],
                channelArray:[],
                tabIndex:0,
                allCategory:[],
                autoSaveTag:false,
                saveTime: new Date(),
                enterPro:[],
                timeSet:null
            };
        },
        watch: {
            '$route'(val, oldVal) {
                this.createForm();
            }
        },
        computed: {
            titleText() {
                return (this.$route.params.id || this.form.id) ? '编辑' : '发布新';
            },
            categoriesText() {
                return this.types
                    .filter(el => el)
                    .map(ele => this.findName(ele));
            },
        },
        methods: {
            channelReset(val){
                console.log(val)
                this.category = val.resetList
                this.channelArray = val.resetSelected
            },
            channelSearch(val){
                console.log(val)
                API.get('application/channel/select?appId=' + val.id+'&kw='+val.kw)
                    .then(res => {
                        console.log(res.cats)
                        this.allCategory = res
                        this.category = res.cats
                        // console.log(res)
                        // let format = formatCategorise(cloneDeep(res.cats), null);
                        // console.log(format)
                    })
                    .catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                       
                    });
            },
            onDel(id){
                Ele.$confirm('确定删除该关联入驻产品？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _data = {
                        appIds:this.form.id,
                        productid:id
                    }
                    // _data.appIds = JSON.stringify(_data.appIds)
                    // _data.productid = JSON.stringify(_data.productid)
                    // _data = JSON.stringify(_data)
                    // console.log(_data)
                    API['delete']('product/application',{data: _data} ).then(res => {
                        console.log(res)
                        Ele.$message.success('操作成功！');
                    }).catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                        this.getEnterPro()
                        //this.$refs.productList.close()
                    });
                }).catch(() => {
                    Ele.$message('取消');
                });
            },
            getEnterPro(){
                let _data = {
                    appId:this.form.id,
                    
                }
                API['get']('application/product?appId='+this.form.id+'&type=self').then(res => {
                        console.log(res)
                        this.enterPro = res
                    }).catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                        this.$refs.productList.close()
                    });
            },
            selectedPro($event){
                console.log($event)

                if($event.length > 0){
                    let _arry = $event.map(item=>{
                        return item._id
                    })
                    console.log(_arry)
                    let _data = {
                        appId:this.form.id,
                        productIds:_arry.join(',')
                    }
                    API['post']('application/product', _data).then(res => {
                        console.log(res)
                        Ele.$message.success(res);
                    }).catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                        this.getEnterPro()
                        this.$refs.productList.close()
                    });
                }
            },
            autoSave(){
                // 校验： 分类、标题、正文
                if (!this.form.title) return false;
                if (!this.form.html) return false;
                // handle data
                this.form.audit = 0;
                this.form.type = 1
                // handle html img width & height
                if (!this.form.html.includes('<!DOCTYPE html>')) {
                    this.form.html = '<!DOCTYPE html>'
                        + '<html>'
                        + '<head>'
                        + '<meta charset=utf-8>'
                        + '<meta http-equiv=X-UA-Compatible content="IE=edge">'
                        + '<meta name="viewport" content="width=device-width, '
                        + 'initial-scale=1,maximum-scale=1, user-scalable=no">'
                        + '<meta http-equiv=Content-Type content="text/html; charset=UTF-8">'
                        + '<title></title>'
                        + '<style type="text/css">'
                        + '* { font-size: 16px;}'
                        + 'body {line-height: 1.5; font-size: 16px; font-family: -apple-system,SF UI Text,Arial,'
                        + 'Hiragino Sans GB,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif; color: #2f2f2f; }'
                        + 'p, div {line-height: 1.7; text-align: justify;}'
                        + 'p {margin: 0 0 20px; padding-left: 10px; padding-right: 10px;}'
                        + 'iframe { width: 100%;}'
                        + '</style>'
                        + '</head><body>'
                        + this.form.html
                        + '</body></html>'
                }

                const regexp = /(<!DOCTYPE html>.*<\/head>)|(<.*?>)/g;
                this.form.intro = this.form.html
                    .replace(regexp, '')
                    .replace(/^((&nbsp;)|(&ldquo;)|(&rdquo;)|(\n)|(\s)|(↵))*/g, '')
                    .slice(0, 100) + '...';

                const hasId = this.$route.params.id || this.form.id;
                let method = hasId ? 'put' : 'post';
                let url = 'manage/applications';
                if (hasId) url += '/' + hasId;

                API[method](url, this.form).then(res => {
                    

                    if (!hasId) this.form.id = res._id;
                    this.autoSaveTag = true
                    this.saveTime = new Date();
                    
                });
            },
            dialigClose(){
                // if(this.form.id){
                //     let routerName = 'Application.Finish';
                //     this.$router.push({name: routerName});
                // }else{
                    this.$refs.channel.close()
                    this.channelArray = []
                // }
            },
            onApply(id){
                API.get('application/channel/select?appId=' + id)
                    .then(res => {
                        console.log(res.cats)
                        this.allCategory = res
                        this.category = res.cats
                        // console.log(res)
                        // let format = formatCategorise(cloneDeep(res.cats), null);
                        // console.log(format)
                    })
                    .catch(err => {
                        Ele.$message.error('操作失败！');
                    })
                    .finally(() => {
                        //this.dialogVisible = false;
                        this.$refs.channel.open(id)
                    });
                
            },
            confirmChannel(){
                
                    let _data = this.channelArray.map(item=>{
                        item.channelApplyStatus = item.channelApplyStatus == 5 ? 1 : item.channelApplyStatus
                        item.appId = id
                        item.channelId = item.id
                        return item
                    })

                    API.post('application/channel/apply', _data)
                        .then(res => {
                            Ele.$message.success('投稿成功');
                        })
                        .catch(err => {
                            Ele.$message.error('投稿失败');
                        })
                        .finally(() => {
                            this.$refs.channel.close()
                            this.channelArray = []
                            // if (!audit) {
                            //     Ele.$message.success('保存成功');
                            // } else {
                            //     Ele.$message.success('发布新应用成功');
                            // }
                            let routerName = 'Application.Finish';
                            this.$router.push({name: routerName});
                        });
                
            },
            channelTypeChange(val){
                if(val == "其它频道"){
                    this.category = this.allCategory.others
                }else{
                    this.category = this.allCategory.cats
                }
            },
            submitData(){
                // 校验： 分类、标题、正文
                if (!this.form.title) return Ele.$message.error('标题不能为空');
                if (!this.form.html) return Ele.$message.error('正文不能为空');
                // handle data
                const typesArr = this.types.filter(el => el);
                this.form.catIds = typesArr.map(el => el[el.length - 1]).join(',');
                this.form.catNames = typesArr.map(el => {
                    return this.findName(el);
                }).join(',');
                this.form.audit = 0;
                this.form.type = 1
                // handle html img width & height
                if (!this.form.html.includes('<!DOCTYPE html>')) {
                    this.form.html = '<!DOCTYPE html>'
                        + '<html>'
                        + '<head>'
                        + '<meta charset=utf-8>'
                        + '<meta http-equiv=X-UA-Compatible content="IE=edge">'
                        + '<meta name="viewport" content="width=device-width, '
                        + 'initial-scale=1,maximum-scale=1, user-scalable=no">'
                        + '<meta http-equiv=Content-Type content="text/html; charset=UTF-8">'
                        + '<title></title>'
                        + '<style type="text/css">'
                        + '* { font-size: 16px;}'
                        + 'body {line-height: 1.5; font-size: 16px; font-family: -apple-system,SF UI Text,Arial,'
                        + 'Hiragino Sans GB,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif; color: #2f2f2f; }'
                        + 'p, div {line-height: 1.7; text-align: justify;}'
                        + 'p {margin: 0 0 20px; padding-left: 10px; padding-right: 10px;}'
                        + 'iframe { width: 100%;}'
                        + '</style>'
                        + '</head><body>'
                        + this.form.html
                        + '</body></html>'
                }

                const regexp = /(<!DOCTYPE html>.*<\/head>)|(<.*?>)/g;
                this.form.intro = this.form.html
                    .replace(regexp, '')
                    .replace(/^((&nbsp;)|(&ldquo;)|(&rdquo;)|(\n)|(\s)|(↵))*/g, '')
                    .slice(0, 100) + '...';

                const hasId = this.$route.params.id || this.form.id;
                let method = hasId ? 'put' : 'post';
                let url = 'manage/applications';
                if (hasId) url += '/' + hasId;

                API[method](url, this.form).then(res => {
                    

                    if (!hasId) this.form.id = res._id;
                    
                })
                .catch(err => {
                    Ele.$message.error('操作失败！');
                })
                .finally(() => {
                   this.onApply(this.form.id)
                    
                });
            },
            tabChange(index){
                if(index){
                    if(!this.form.id){
                        Ele.$message.error('请先保存应用再进行产品关联！');
                        return false
                    }
                    this.getEnterPro()
                }
                this.tabIndex = index
            },
            createForm() {
                this.form = {
                    catIds: '', // 类目id    string  多个用,分格
                    catNames: '',  // 类目名称    string  多个用,分格
                    img: '',
                    title: '', // 标题
                    html: '', // 富文本信息   string
                    hide: false, // 是否匿名发布  boolean
                    labels: [], //应用标签    string  多个用,分格
                    audit: 0
                };

                this.types = new Array(1);
            },
            addCategory() {
                if (this.types.length >= 5) {
                    Ele.$message.error('最多添加5个分类');
                    return;
                }

                this.types.push(undefined);
            },
            removeLabel(index) {
                this.labels.splice(index, 1);
            },
            async fetchCategory() {
                const categories = await getCategorise('cascader');
                console.log(categories)
                this.category = categories
                this.typeOptions = categories.map(el => {
                    if (!el.nodes) el.disabled = true;
                    return el;
                });
                this.options = await getCategorise();
            },
            fetchDetail() {
                API.get('applications/' + this.$route.params.id).then(res => {
                    this.form = res;

                    // 处理html, 移除style标签与样式
                    const regexp = /(<!DOCTYPE html>.*<\/head>)/g;
                    this.form.html = res.html.replace(regexp, '');

                    // for (let key in res) {
                    //     if (this.form.hasOwnProperty(key)) {
                    //         this.form[key] = res[key];
                    //     }
                    // }
                    this.types = res.cats.map(el => this.findCategoryArray(el.catId));
                    this.labels = res.labels.filter(el => el);
                    this.form.labels = res.labels.filter(el => el);
                });
            },
            findCategoryArray(sourceId) {
                const options = this.options;
                let arr = [];
                let isFinish = true;
                let id = sourceId;

                while (isFinish) {
                    const element = options.find(el => el.id === id);
                    if (element) {
                        arr.unshift(element.id);
                        if (element.parentid) {
                            id = element.parentid;
                        } else {
                            isFinish = false;
                        }
                    } else {
                        isFinish = false;
                    }
                }
                return arr;
            },
            postData(audit) {
                // 校验： 分类、标题、正文
                if (!this.form.title) return Ele.$message.error('标题不能为空');
               // const testTypes = this.types.filter(el => el && el.length);
               // if (!testTypes.length) return Ele.$message.error('分类不能为空');
                if (!this.form.html) return Ele.$message.error('正文不能为空');

                // handle data
                const typesArr = this.types.filter(el => el);
                this.form.catIds = typesArr.map(el => el[el.length - 1]).join(',');
                this.form.catNames = typesArr.map(el => {
                    return this.findName(el);
                }).join(',');
                this.form.audit = audit;
                this.form.type = 1
                // handle html img width & height
                if (!this.form.html.includes('<!DOCTYPE html>')) {
                    this.form.html = '<!DOCTYPE html>'
                        + '<html>'
                        + '<head>'
                        + '<meta charset=utf-8>'
                        + '<meta http-equiv=X-UA-Compatible content="IE=edge">'
                        + '<meta name="viewport" content="width=device-width, '
                        + 'initial-scale=1,maximum-scale=1, user-scalable=no">'
                        + '<meta http-equiv=Content-Type content="text/html; charset=UTF-8">'
                        + '<title></title>'
                        + '<style type="text/css">'
                        + '* { font-size: 16px;}'
                        + 'body {line-height: 1.5; font-size: 16px; font-family: -apple-system,SF UI Text,Arial,'
                        + 'Hiragino Sans GB,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif; color: #2f2f2f; }'
                        + 'p, div {line-height: 1.7; text-align: justify;}'
                        + 'p {margin: 0 0 20px; padding-left: 10px; padding-right: 10px;}'
                        + 'iframe { width: 100%;}'
                        + '</style>'
                        + '</head><body>'
                        + this.form.html
                        + '</body></html>'
                }

                const regexp = /(<!DOCTYPE html>.*<\/head>)|(<.*?>)/g;
                this.form.intro = this.form.html
                    .replace(regexp, '')
                    .replace(/^((&nbsp;)|(&ldquo;)|(&rdquo;)|(\n)|(\s)|(↵))*/g, '')
                    .slice(0, 100) + '...';

                const hasId = this.$route.params.id || this.form.id;
                let method = hasId ? 'put' : 'post';
                let url = 'manage/applications';
                if (hasId) url += '/' + hasId;

                API[method](url, this.form).then(res => {
                    if (!audit) {
                        Ele.$message.success('保存成功');
                    } else {
                        Ele.$message.success('发布新应用成功');
                    }

                    let routerName = 'Application.Ready';
                    this.$router.push({name: routerName});

                    if (!hasId) this.form.id = res._id;

                    // if (audit) {
                    //     if (this.$route.params.id) {
                    //         LocalStore.set('ready_modify_' + this.$route.params.id, 'finish');
                    //     }

                    //     let routerName = 'Application.' + (audit ? 'Wait' : 'Ready');
                    //     this.$router.push({name: routerName});
                    // }

                    // const regexp = /(<!DOCTYPE html>.*<\/head>)/g;
                    // this.form.html = this.form.html.replace(regexp, '');
                });
            },
            findName(array) {
                return this.options.find(el => el.id === array[array.length - 1]).text;
            },
        },
        mounted() {
            bus.$on('collapse-observe', (value) => {
              // ...
                console.log('collapse-observe', value);
                this.isCollapse = value;
            })
            
        },
        created() {
            this.createForm();
            if (this.$route.params.id) this.fetchDetail();
        },
        beforeRouteEnter(to, from, next) {
            next(vm => {
                vm.fetchCategory();
                window.timeSet = setInterval(()=>{
                    vm.autoSave()
                },1000*30)
            });
        },
        beforeRouteLeave(to, from, next) {
            if(window.timeSet){
                clearInterval(window.timeSet)
            }
            next();
        }
    };
</script>

<style lang="scss">
    .application-edit {
        .el-card__body {
            padding-bottom: 80px;
        }

        header {
            color: #333;
            font-size: 20px;
        }
        &-tab{
            
        }

        &-tabitem{
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            border-bottom: 2px solid #efefef;
            color: #ccc;
        }

        &-tabitem.active{
            color: #02a7fb;
            border-bottom: 4px solid #02a7fb;
        }

        &__upload {
            max-height: 250px;
            margin: 18px auto 12px;

            .default {
                color: #999;
                height: 150px;
                font-size: 14px;
                padding-top: 30px;
                background-color: #ececec;

                .iconfont {
                    font-size: 40px;
                }
            }

            .active {
                // height: 500px;
                text-align: center;

                .delete-icon {
                    position: absolute;
                    right: -15px;
                    top: -12px;
                    background: #fff;
                    border-radius: 50%;

                    .el-icon-error {
                        color: #666;
                        font-size: 30px;
                    }
                }
            }
        }

        &__title {
            width: 100%;
            height: 46px;
            font-size: 22px;
            line-height: 46px;
            margin-bottom: 20px;
            &::placeholder-text {
                color: #999;
            }
        }

        &__tags {
            width: 100%;
            min-height: 40px;
            font-size: 16px;
            line-height: 40px;
            margin-bottom: 20px;

            .el-input__inner {
                border: 0;
                border-radius: 0;
            }

            &.el-select .el-tag {
                padding: 4px 10px;
                height: 32px;
                font-size: 13px;
            }

            .el-input__suffix {
                display: none;
            }
        }

        &__control {
            position: fixed;
            bottom: 21px;
            background: #fff;
            padding: 1rem;
            transition: all .6s;

            &.create-collaspe {
                width: calc(100% - 40px);
                left: 20px;
            }

            &.is-collaspe {
                width: calc(100% - 130px);
                left: 110px;
            }

            &.no-collaspe {
                width: calc(100% - 330px);
                left: 300px;
            }
        }
    }
</style>
